package com.jy.admin.services.cashPocket;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.Md5Utils;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.MD5;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.jy.admin.config.ApolloConfigUtil;
import com.jy.admin.db.dao.*;
import com.jy.admin.db.entity.*;
import com.jy.admin.enums.ApiTypeEnum;
import com.jy.admin.enums.LittleOrangeCashCollectionTagEnum;
import com.jy.admin.enums.OrderStatusEnum;
import com.jy.admin.enums.OrderSyncStatusEnum;
import com.jy.admin.jobs.BaseJobHandler;
import com.jy.admin.services.BaseCrawlerService;
import com.jy.admin.services.cashPocket.vo.ClOrderInputVo;
import com.jy.admin.services.cashPocket.vo.ClOrderReceiveRequest;
import com.jy.admin.services.cashPocket.vo.ClRepaymentRequest;
import com.jy.admin.services.cashPocket.vo.ClUserInfoInputVo;
import com.jy.bo.common.conf.api.ApiResponse;
import com.jy.bo.common.conf.util.HttpUtil;
import com.robert.vesta.util.IdUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.util.*;
import java.util.concurrent.*;

import static com.jy.admin.services.cashPocket.SivanWalletService.execCurl;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2022/1/3
 * Time: 8:46 下午
 */
@Service
public class LittleOrangeService extends BaseCrawlerService {
    private static final Logger LOGGER = LoggerFactory.getLogger(LittleOrangeService.class);

    @Autowired
    private CeOrdersDetailDao ordersDetailDao;

    @Autowired
    private CeMerchantDao merchantDao;

    @Autowired
    private CeCommentPushLogDao commentPushLogDao;

    @Autowired
    private CeAgentAccountDao agentAccountDao;

    @Autowired
    private ApolloConfigUtil apolloConfigUtil;

    @Autowired
    private CeRepaymentLinkDao repaymentLinkDao;


    @PostConstruct
    public void init() {
        BaseJobHandler.merchantAndServiceMap.put("littleorange", this);
        BaseJobHandler.merchantAndServiceMap.put("bo", this);
        BaseJobHandler.merchantAndServiceMap.put("bee", this);
    }

    public String login(CeAgentAccountEntity agentAccount, String code) {
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());

        Map<String, String> headers = getHeaders(agentAccount);
        headers.remove("auth");
        JSONObject params = new JSONObject();
        params.put("model", code);
        String url = merchant.getApiDomain() + "/api/verify_code/verify_second";
        String[] command = {"curl", "--location", "--request", "POST", url,
                "--header", "lang: en-us",
                "--header", "customer: 3XELTZUO",
                "--header", "Referer: https://client.eivxmsffjgbin.com/login",
                "--header", "accept: application/json",
                "--header", "accept-encoding: gzip, deflate, br",
                "--header", "accept-language: zh-CN,zh;q=0.9",
                "--header", "content-type: application/json; charset=utf-8",
                "--header", "origin: " + merchant.getApiDomain(),
                "--header", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"",
                "--header", "sec-ch-ua-mobile: ?0",
                "--header", "sec-ch-ua-platform: \"macOS\"",
                "--header", "sec-fetch-dest: empty",
                "--header", "sec-fetch-mode: cors",
                "--header", "sec-fetch-site: same-origin",
                "--header", "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
                "--data-raw", params.toString()};
        String result = execCurl(command);

        String loginUrl = merchant.getApiDomain() + "/api/auth/login";
        JSONObject loginParams = new JSONObject();
        loginParams.put("customer", "3XELTZUO");
        loginParams.put("username", agentAccount.getAccount());
        loginParams.put("password", agentAccount.getPassword());
        loginParams.put("code", JsonIterator.deserialize(result).get("model").toString());
        loginParams.put("remember", true);
        String[] loginCommand = {"curl", "--location", "--request", "POST", loginUrl,
                "--header", "lang: en-us",
                "--header", "customer: 3XELTZUO",
                "--header", "Referer: https://client.eivxmsffjgbin.com/login",
                "--header", "accept: application/json",
                "--header", "accept-encoding: gzip, deflate, br",
                "--header", "accept-language: zh-CN,zh;q=0.9",
                "--header", "content-type: application/json; charset=utf-8",
                "--header", "origin: " + merchant.getApiDomain(),
                "--header", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"",
                "--header", "sec-ch-ua-mobile: ?0",
                "--header", "sec-ch-ua-platform: \"macOS\"",
                "--header", "sec-fetch-dest: empty",
                "--header", "sec-fetch-mode: cors",
                "--header", "sec-fetch-site: same-origin",
                "--header", "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
                "--data-raw", loginParams.toString()};
        String loginResult = execCurl(loginCommand);
        LOGGER.info("== 登录结果 ==,loginResult:{}", loginResult);
        Any loginResultJson = JsonIterator.deserialize(loginResult);
        if (loginResultJson.get("status").toInt() == 0) {
            LOGGER.info("== 登录成功 ==,agentCode:{},loginResult:{}", agentAccount.getAgentCode(), loginResult);
            JSONObject requestHeader = new JSONObject();
            requestHeader.put("auth", loginResultJson.get("user").get("token").toString());
            agentAccount.setRequestHeader(requestHeader.toString());
            agentAccount.setLoginDt(new Date());
            agentAccount.setLoginStatus(1);
            agentAccountDao.updateByPrimaryKey(agentAccount);
            return "登陆成功";
        } else {
            LOGGER.info("== 登录失败 ==,agentCode:{},loginResult:{}", agentAccount.getAgentCode(), loginResult);
            return "登录失败";
        }
//        return loginResult;
    }

    @Override
    public boolean hasLogin(CeAgentAccountEntity agentAccount) {
        if (apolloConfigUtil.isLoginStatusUseCache()) {
            return agentAccount.getLoginStatus() == 1;
        }

        if (agentAccount.getLoginStatus() == 2) {
            LOGGER.error("== 账号 token不可用 ==,account:{}", agentAccount.getAccount());
            return false;
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + "/api/cm_dunning_case/user_dunning_case_info";
        LOGGER.info("== 开始检测Token是否有效 ==,url:{}", url);
        long st = System.currentTimeMillis();
        String stt = MD5.md5("#cG8wbGttMW5ibG16eDZoYQ#3XELTZUO#" + st);
        Map<String, String> headers = getHeaders(agentAccount);
        String[] cmds = {"curl", "--location", "--request", "POST", url,
                "--header", "Content-Type: application/json",
                "--header", "lang: en-us",
                "--header", "customer: 3XELTZUO",
                "--header", "auth:" + headers.get("auth"),
                "--header", "Referer: " + merchant.getApiDomain() + "/cm-dunning-case-list",
                "--header", "accept: application/json",
                "--header", "accept-encoding: gzip, deflate, br",
                "--header", "accept-language: zh-CN,zh;q=0.9",
                "--header", "content-type: application/json; charset=utf-8",
                "--header", "origin: " + merchant.getApiDomain(),
                "--header", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"",
                "--header", "st:" + st,
                "--header", "stt:" + stt,
                "--header", "sec-ch-ua-mobile: ?0",
                "--header", "sec-ch-ua-mobile: ?0",
                "--header", "sec-ch-ua-platform: \"macOS\"",
                "--header", "sec-fetch-dest: empty",
                "--header", "sec-fetch-mode: cors",
                "--header", "sec-fetch-site: same-origin",
                "--header", "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
                "--data-raw", new JSONObject().toString()};
        String result = execCurl(cmds);
        LOGGER.info("== 结束检测Token是否有效 ==,result:{}", result);

        if (JsonIterator.deserialize(result).get("status").toInt() != 0) {
            LOGGER.error("== 请求接口数据出错 当前账号token无效==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.user_info.getType());
            agentAccount.setLoginStatus(2);
            agentAccountDao.updateByPrimaryKey(agentAccount);
            return false;
        }
        return true;
    }

    @Override
    public void refresh(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== CashWorldService 开始刷新数据 ==,account:{}", agentAccount.getAccount());
        updateOrderList(agentAccount);

        LOGGER.info("== 订单数据更新完成 开始更新订单关联数据==，account:{}", agentAccount.getAccount());
        updateOrderDetailInfo(agentAccount);

        LOGGER.info("== 订单关联数据已经更新完成==，account:{}", agentAccount.getAccount());
    }

    public static String execCurl(String[] cmds) {
        ProcessBuilder process = new ProcessBuilder(cmds);
        Process p;
        try {
            p = process.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
                builder.append(System.getProperty("line.separator"));
            }
            return builder.toString();

        } catch (IOException e) {
            System.out.print("error");
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void updateOrderList(CeAgentAccountEntity agentAccount) {
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + "/api/cm_dunning_case/page";
        LOGGER.info("== 开始请求订单列表 ==,url:{}", url);
        Map<String, String> headers = getHeaders(agentAccount);
        List<Any> resultsList = Lists.newArrayList();
        int pageSize = 100;
        for (int i = 1; i < 10; i++) {
            JSONObject params = new JSONObject();
            JSONObject param = new JSONObject();
            param.put("pageNo", i);
            param.put("pageSize", pageSize);
            param.put("status", "PENDING");
            param.put("filterAllCase", false);
            JSONObject childParams = new JSONObject();
            childParams.put("userInfo", new JSONObject());
            param.put("orderQuery", childParams);
            params.put("query", param);
            long st = System.currentTimeMillis();
            String stt = MD5.md5("#cG8wbGttMW5ibG16eDZoYQ#3XELTZUO#" + st);
            LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(params));
            String[] cmds = {"curl", "--location", "--request", "POST", url,
                    "--header", "Content-Type: application/json",
                    "--header", "lang: en-us",
                    "--header", "customer: 3XELTZUO",
                    "--header", "auth:" + headers.get("auth"),
                    "--header", "Referer: " + merchant.getApiDomain() + "/cm-dunning-case-list",
                    "--header", "accept: application/json",
                    "--header", "accept-encoding: gzip, deflate, br",
                    "--header", "accept-language: zh-CN,zh;q=0.9",
                    "--header", "content-type: application/json; charset=utf-8",
                    "--header", "st:" + st,
                    "--header", "stt:" + stt,
                    "--header", "origin: " + merchant.getApiDomain(),
                    "--header", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"",
                    "--header", "sec-ch-ua-mobile: ?0",
                    "--header", "sec-ch-ua-platform: \"macOS\"",
                    "--header", "sec-fetch-dest: empty",
                    "--header", "sec-fetch-mode: cors",
                    "--header", "sec-fetch-site: same-origin",
                    "--header", "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
                    "--data-raw", params.toString()};
            String result = execCurl(cmds);
            int status = JsonIterator.deserialize(result).get("status").toInt();
            if (status != 0) {
                LOGGER.error("== 订单列表请求接口数据出错 ==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
                return;
            }
            Any resultJson = JsonIterator.deserialize(result).get("page");
            List<Any> list = resultJson.get("content").asList();
            resultsList.addAll(list);
            if (list.size() < pageSize) {
                break;
            }
        }

        LOGGER.info("== LittleOrange未还款订单列表 ==,screeningList:{}", JsonStream.serialize(resultsList));
        LOGGER.info("== LittleOrange未还款订单列表数量 ==,size:{}", resultsList.size());


        //查询今天该账号的所有有效订单
        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());

        //更新数据
        LOGGER.info("==当天已经有数据 ==，size:{}", activeOrders.size());

        //对比订单数据
        if (resultsList.size() >= activeOrders.size()) {
            LOGGER.info("== 存在未拉取订单 ==，size:{}", resultsList.size());
            resultsList.forEach(item -> {
                try {
                    String orderNo = item.get("cmOrderId").toString();
                    CeOrdersEntity todayOneByOrderNo = ordersDao.getTodayOneByOrderNoAndAgentCode(orderNo, agentAccount.getAgentCode());
                    if (todayOneByOrderNo == null) {
                        LOGGER.info("==更新的时候发现有新的订单==,account:{},orderNo:{}", agentAccount.getAccount(), orderNo);
                        CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                                .setAgentCode(agentAccount.getAgentCode())
                                .setMerchantCode(agentAccount.getMerchantCode())
                                .setOrderNo(orderNo)
                                .setOrderInfo(item.toString())
                                .setStatus(OrderStatusEnum.active.getStatus())
                                .setCreateDt(new Date())
                                .setCollectionNo(IdUtils.genId() + "");
                        ordersDao.insert(ceOrdersEntity);
                    } else {
                        LOGGER.info("==更新的时候订单的已存在==,agentCode:{},orderNo:{}", todayOneByOrderNo.getAgentCode(), orderNo);
                        if (item.get("status").toString().equals("SUCCESS")) {
                            LOGGER.info("==更新的时候订单的已存在，状态为已还款==,account:{},orderNo:{},status:{}", todayOneByOrderNo.getAgentCode(), orderNo, item.get("repaymentStatus").toString());
                            todayOneByOrderNo.setOrderInfo(item.toString()).setStatus(OrderStatusEnum.updated.getStatus());
                            ordersDao.updateByPrimaryKey(todayOneByOrderNo);
                        }
                    }
                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,account:{},loanId:{}", agentAccount.getAccount(), item.get("loanAppId").toString(), e);
                }
            });
        } else {
            LOGGER.info("== 订单减少 ==，size:{}", resultsList.size());
            activeOrders.forEach(item -> {
                try {
                    String id = JsonIterator.deserialize(item.getOrderInfo()).get("cmOrderId").toString();
                    boolean hasOrder = false;
                    Any currentOrder = null;
                    for (int i = 0; i < resultsList.size(); i++) {
                        Any child = resultsList.get(i);
                        String orderNo = child.get("cmOrderId").toString();
                        if (id.equals(orderNo)) {
                            LOGGER.info("== 当前订单存在 ==,account:{},orderNo:{}", agentAccount.getAccount(), orderNo);
                            hasOrder = true;
                            currentOrder = child;
                            break;
                        }

                    }
                    if (!hasOrder) {
                        LOGGER.info("== 当前订单不存在 ==,account:{},orderNo:{}", agentAccount.getAccount(), id);
                        if (item.getStatus().equals(OrderStatusEnum.active.getStatus())) {
                            item.setStatus(OrderStatusEnum.updated.getStatus());
                            ordersDao.updateByPrimaryKey(item);
                        }
                    } else {
                        LOGGER.info("==更新的时候订单的已存在==,agentCode:{},orderNo:{}", item.getAgentCode(), id);
                        if (currentOrder.get("status").toString().equals("SUCCESS")) {
                            LOGGER.info("==更新的时候订单的已存在，状态为已还款==,account:{},orderNo:{},status:{}", agentAccount.getAccount(), id, currentOrder.get("repaymentStatus").toString());
                            item.setOrderInfo(currentOrder.toString()).setStatus(OrderStatusEnum.updated.getStatus());
                            ordersDao.updateByPrimaryKey(item);
                        }
                    }
                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,account:{},orderNo:{}", agentAccount.getAccount(), JsonIterator.deserialize(item.getOrderInfo()).get("id").toString(), e);
                }
            });

        }
        LOGGER.info("== 订单刷新处理完成 ==");
    }

    @Override
    public void updateOrderDetailInfo(CeAgentAccountEntity agentAccount) {

        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());
        if (CollectionUtils.isEmpty(activeOrders)) {
            return;
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());

        Map<String, String> headers = getHeaders(agentAccount);

        activeOrders.forEach(order -> {

            try {
                boolean hasDetailData = order.getDetailStatus() == 1;
                Map<String, String> infoMap = new HashMap<>();
                Any orderInfo = JsonIterator.deserialize(order.getOrderInfo());
                if (!hasDetailData) {
                    String cmOrderId = orderInfo.get("cmOrderId").toString();
                    JSONObject params = new JSONObject();
                    params.put("id", cmOrderId);
                    long st = System.currentTimeMillis();
                    String stt = MD5.md5("#cG8wbGttMW5ibG16eDZoYQ#3XELTZUO#" + st);
                    String repaymentInfoUrl = merchant.getApiDomain() + "/api/cm_order/one";
                    String[] repaymentCmds = {"curl", "--location",
                            "--request", "POST", repaymentInfoUrl,
                            "--header", "Content-Type: application/json",
                            "--header", "lang: en-us",
                            "--header", "customer: 3XELTZUO",
                            "--header", "auth:" + headers.get("auth"),
                            "--header", "Referer: " + merchant.getApiDomain() + "/cm-dunning-case-list",
                            "--header", "accept: application/json",
                            "--header", "accept-encoding: gzip, deflate, br",
                            "--header", "accept-language: zh-CN,zh;q=0.9",
                            "--header", "content-type: application/json; charset=utf-8",
                            "--header", "st:" + st,
                            "--header", "stt:" + stt,
                            "--header", "origin: " + merchant.getApiDomain(),
                            "--header", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"",
                            "--header", "sec-ch-ua-mobile: ?0",
                            "--header", "sec-ch-ua-platform: \"macOS\"",
                            "--header", "sec-fetch-dest: empty",
                            "--header", "sec-fetch-mode: cors",
                            "--header", "sec-fetch-site: same-origin",
                            "--header", "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
                            "--data-raw", params.toString()};
                    String repaymentInfoResult = execCurl(repaymentCmds);
                    LOGGER.info("== 获取成功 repaymentInfo==");
                    if (repaymentInfoResult == null) {
                        LOGGER.info("== 订单详情error==,orderNo:{}", cmOrderId);
                        return;
                    }
                    if (JsonIterator.deserialize(repaymentInfoResult).get("status").toInt() != 0) {
                        LOGGER.info("== 订单详情error==,orderNo:{}", cmOrderId);
                        return;
                    }
                    Any repaymentInfo = JsonIterator.deserialize(repaymentInfoResult).get("model");
                    infoMap.put("repaymentInfo", JsonStream.serialize(repaymentInfo));
                    String remainMoney = repaymentInfo.get("needRepayAmount").toString();
                    if (!remainMoney.equals("0")) {
                        LOGGER.info("== 还款金额 remainMoney==,remainMoney:{},orderNo:{}", remainMoney, cmOrderId);
                    }
                    updateRemainMoney(order.getCollectionNo(), remainMoney);

                    CeOrdersDetailEntity baseInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "baseInfo", order.getOrderNo());
                    if (baseInfoDetail == null) {
                        Any loanAuditOrder = repaymentInfo.get("userInfo");
                        infoMap.put("baseInfo", loanAuditOrder.toString());
                        LOGGER.info("== 获取成功 baseInfo==");
                    } else {
                        baseInfoDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(baseInfoDetail);
                    }

                    CeOrdersDetailEntity contactInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactInfo", order.getOrderNo());
                    if (contactInfoDetail == null) {
                        List<Any> loanAuditOrder = repaymentInfo.get("userInfo").get("userEmergs").asList();
                        ArrayList<JSONObject> list = Lists.newArrayList();
                        for (int i = 0; i < loanAuditOrder.size(); i++) {
                            JSONObject json = new JSONObject();
                            json.put("name", loanAuditOrder.get(i).get("name").toString().equals("") ? "no" : loanAuditOrder.get(i).get("name").toString());
                            if (!loanAuditOrder.get(i).get("phone").toString().equals("")) {
                                json.put("phone", loanAuditOrder.get(i).get("phone").toString());
                                list.add(json);
                            }

                        }
                        LOGGER.info("== 获取成功 contactInfo==");
                        infoMap.put("contactInfo", list.toString());
                    } else {
                        contactInfoDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(contactInfoDetail);
                    }


                    String imageUrl = merchant.getApiDomain() + "/api/cm_user_auth_data/list";
                    JSONObject imageParams = new JSONObject();
                    JSONObject imageParam = new JSONObject();
                    imageParam.put("cmOrderId", repaymentInfo.get("cmDunningCase").get("cmOrderId").toString());
                    imageParam.put("cmAppUserId", repaymentInfo.get("cmAppUserId").toString());
                    JSONArray imageArray = new JSONArray();
                    JSONObject child = new JSONObject();
                    child.put("field", "created");
                    child.put("sort", 1);
                    imageArray.add(child);
                    imageParam.put("sortFields", imageArray);
                    imageParams.put("query", imageParam);
                    String[] imageCmds = {"curl", "--location", "--request", "POST", imageUrl,
                            "--header", "Content-Type: application/json",
                            "--header", "lang: en-us",
                            "--header", "customer: 3XELTZUO",
                            "--header", "auth:" + headers.get("auth"),
                            "--header", "Referer: " + merchant.getApiDomain() + "/cm-dunning-case-list",
                            "--header", "accept: application/json",
                            "--header", "accept-encoding: gzip, deflate, br",
                            "--header", "accept-language: zh-CN,zh;q=0.9",
                            "--header", "content-type: application/json; charset=utf-8",
                            "--header", "st:" + st,
                            "--header", "stt:" + stt,
                            "--header", "origin: " + merchant.getApiDomain(),
                            "--header", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"",
                            "--header", "sec-ch-ua-mobile: ?0",
                            "--header", "sec-ch-ua-platform: \"macOS\"",
                            "--header", "sec-fetch-dest: empty",
                            "--header", "sec-fetch-mode: cors",
                            "--header", "sec-fetch-site: same-origin",
                            "--header", "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
                            "--data-raw", imageParams.toString()};
                    String imageInfoResult = execCurl(imageCmds);
                    Any imageInfo = JsonIterator.deserialize(imageInfoResult);
                    if (imageInfo.get("status").toInt() != 0) {
                        return;
                    }
                    if (imageInfo.get("list").asList().size() > 0) {
                        Any userAuthInfo = imageInfo.get("list").asList().get(0);
                        List<String> images = Lists.newArrayList();
                        if (!userAuthInfo.get("idCardImageFront").toString().equals("")) {
                            images.add(userAuthInfo.get("idCardImageFront").toString());
                        }
                        if (!userAuthInfo.get("idCardImageBack").toString().equals("")) {
                            images.add(userAuthInfo.get("idCardImageBack").toString());
                        }
                        if (!userAuthInfo.get("idCardImagePan").toString().equals("")) {
                            images.add(userAuthInfo.get("idCardImagePan").toString());
                        }
                        infoMap.put("images", JsonStream.serialize(images));
                        LOGGER.info("== 获取成功 images==");
                    }

                    CeOrdersDetailEntity contactUrlDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());
                    if (contactUrlDetail == null) {
                        List<Any> contactList = Lists.newArrayList();
                        for (int i = 1; i < 3; i++) {
                            JSONObject contactInfoParams = new JSONObject();
                            JSONObject contactInfoParam = new JSONObject();
                            contactInfoParam.put("pageNo", i);
                            contactInfoParam.put("pageSize", 100);
                            contactInfoParam.put("androidId", repaymentInfo.get("imei").toString());
                            contactInfoParam.put("orderId", repaymentInfo.get("thirdId").toString());
                            JSONArray array = new JSONArray();
                            JSONObject childOne = new JSONObject();
                            childOne.put("field", "lastTimeContacted");
                            childOne.put("sort", -1);
                            JSONObject childTwo = new JSONObject();
                            childTwo.put("field", "created");
                            childTwo.put("sort", -1);
                            array.add(childOne);
                            array.add(childTwo);
                            contactInfoParam.put("sortFields", array);
                            contactInfoParams.put("query", contactInfoParam);
                            String contactInfoUrl = merchant.getApiDomain() + "/api/g_device_contact/page";
                            String[] contactInfoCmds = {"curl", "--location", "--request", "POST", contactInfoUrl,
                                    "--header", "Content-Type: application/json",
                                    "--header", "lang: en-us",
                                    "--header", "customer: 3XELTZUO",
                                    "--header", "auth:" + headers.get("auth"),
                                    "--header", "Referer: " + merchant.getApiDomain() + "/cm-dunning-case-list",
                                    "--header", "accept: application/json",
                                    "--header", "accept-encoding: gzip, deflate, br",
                                    "--header", "accept-language: zh-CN,zh;q=0.9",
                                    "--header", "content-type: application/json; charset=utf-8",
                                    "--header", "st:" + st,
                                    "--header", "stt:" + stt,
                                    "--header", "origin: " + merchant.getApiDomain(),
                                    "--header", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"",
                                    "--header", "sec-ch-ua-mobile: ?0",
                                    "--header", "sec-ch-ua-platform: \"macOS\"",
                                    "--header", "sec-fetch-dest: empty",
                                    "--header", "sec-fetch-mode: cors",
                                    "--header", "sec-fetch-site: same-origin",
                                    "--header", "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
                                    "--data-raw", contactInfoParams.toString()};
                            String contactInfo = execCurl(contactInfoCmds);
                            LOGGER.info("== 获取LittleOrange联系人==,contactInfo:{}",contactInfo);
                            if (JsonIterator.deserialize(contactInfo).get("status").toInt() != 0) {
                                LOGGER.info("== 获取LittleOrange联系人出错==,agentCode:{}",agentAccount.getAgentCode());
                                break;
                            }
                            contactList.addAll(JsonIterator.deserialize(contactInfo).get("page").get("content").asList());
                            if (JsonIterator.deserialize(contactInfo).get("page").get("totalPages").toInt() < i) {
                                break;
                            }
                        }
                        LOGGER.info("== 获取成功 contactInfo==");

                        try {
                            if (CollectionUtils.isNotEmpty(contactList)) {
                                JSONArray contacts = new JSONArray();
                                for (Any vo : contactList) {
                                    JSONObject j1 = new JSONObject();
                                    j1.put("name", vo.get("name").toString().equals("") ? "no" : vo.get("name").toString());
                                    if (vo.get("phones").asList().size() > 0) {
                                        j1.put("phone", vo.get("phones").asList().get(0).toString().replace(")",""));
                                        contacts.add(j1);
                                    }
                                }
                                JSONObject jsonData = new JSONObject();
                                jsonData.put("contacts", contacts);

                                String contactUrl = uploadContact(order.getOrderNo(), jsonData.toString());
                                LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", contactUrl);
                                infoMap.put("contactUrl", contactUrl);
                            } else {
                                String contacts;
                                if (contactInfoDetail != null) {
                                    contacts = contactInfoDetail.getDetailInfo();
                                } else {
                                    contacts = infoMap.get("contactInfo");
                                }
                                List<Any> anies = JsonIterator.deserialize(contacts).asList();
                                ArrayList<JSONObject> list = Lists.newArrayList();
                                for (int i = 0; i < anies.size(); i++) {
                                    JSONObject json = new JSONObject();
                                    json.put("name", anies.get(i).get("name").toString().equals("") ? "no" : anies.get(i).get("name").toString());
                                    if (!anies.get(i).get("phone").toString().equals("")) {
                                        json.put("phone", anies.get(i).get("phone").toString());
                                        list.add(json);
                                    }

                                }
                                JSONObject jsonData = new JSONObject();
                                jsonData.put("contacts", list.toString());

                                String contactUrl = uploadContact(order.getOrderNo(), jsonData.toString());
                                LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", contactUrl);
                                infoMap.put("contactUrl", contactUrl);
                            }

                        } catch (Exception e) {
                            LOGGER.error("== 通讯录转换错误 ==", e);
                        }
                    } else {
                        contactUrlDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(contactUrlDetail);
                    }

                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        if (byKeyAndMerchantAndOrderNo == null) {
                            CeOrdersDetailEntity ordersDetailEntity = new CeOrdersDetailEntity().setOrderNo(order.getOrderNo()).setMerchantCode(order.getMerchantCode()).setDataKey(k).setDetailInfo(infoMap.get(k));
                            ordersDetailDao.insert(ordersDetailEntity);
                        } else {
                            byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                            ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                        }

                    });
                } else {
                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                        ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                    });
                }

                order.setDetailStatus(1);
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 程序处理有异常 ==", e);
                order.setDetailStatus(2);
                ordersDao.updateByPrimaryKey(order);
            }
        });

        LOGGER.info("== 程序处理完成 ==");
    }

    @Override
    public void compostCollectionData(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== compostCollectionData ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== compostCollectionData  没有需要同步的订单 ==，agentCode:{},syncStatus:{}", agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
            return;
        }

        LOGGER.info("== compostCollectionData  需要同步的订单 ==，size:{},account:{}", todayListBySyncStatusAndAgent.size(), agentAccount.getAccount());

        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                LOGGER.info("== 构建推送信息 基础信息 开始==,collectionNo:{},syncStatus:{}", order.getCollectionNo(), order.getSyncStatus());
                Any orderDetail = JsonIterator.deserialize(order.getOrderInfo());
                CeOrdersDetailEntity repaymentInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                Any repaymentInfo = JsonIterator.deserialize(repaymentInfoDetail.getDetailInfo());

                String appName = repaymentInfo.get("loanAppName").toString() + "[" + repaymentInfo.get("loanAppProductName").toString() + "]";
                ClOrderReceiveRequest request = new ClOrderReceiveRequest().setOrderBillNo(order.getCollectionNo()).setTradeNo(order.getCollectionNo()).setProductType(appName).setAppName(appName).setOriginOrderNo(order.getOrderNo()).setAccount(order.getAgentCode()).setAccount_id(agentAccount.getId()).setClientCode(order.getMerchantCode()).setProductCode(appName).setUserCode(IdUtils.genId() + "");


                String borrowCapital = repaymentInfo.get("totalRepayAmount").toString();
                String actualAmount = repaymentInfo.get("actualAmount").toString();
                String paidAmount = repaymentInfo.get("totalPaidAmount").toString();
                String repaymentAmount = repaymentInfo.get("totalRepayAmount").toString();
                String remainMoney = repaymentInfo.get("needRepayAmount").toString();
                String serviceAmount = repaymentInfo.get("serviceAmount").toString();
                String loanAppUrl = repaymentInfo.get("loanAppUrl").toString();
                String overdueDays = repaymentInfo.get("repaymentInfo").get("overdueCount").toString();
                String lateFee = repaymentInfo.get("repaymentInfo").get("overdueAmount").toString();

                LOGGER.info("== 构建推送信息 计算逾期罚息利率 开始==,borrowCapital:{}，overdueDays:{}.lateFee:{}", borrowCapital, overdueDays, lateFee);
                String overdueRatio = "0";
                if (!overdueDays.equals("0")) {
                    overdueRatio = new BigDecimal(lateFee).divide(new BigDecimal(overdueDays), 2, BigDecimal.ROUND_HALF_UP).divide(new BigDecimal(borrowCapital), 4, BigDecimal.ROUND_HALF_UP).toString();
                }
                LOGGER.info("== 构建推送信息 订单信息 开始==,collectionNo:{}", order.getCollectionNo());
                ClOrderInputVo orderInputVo = new ClOrderInputVo()
                        .setBorrowType(repaymentInfo.get("currentReloan").toInt() == 0 ? 1 : 2)
                        .setBorrowCapital(borrowCapital)
                        .setChannel(appName)
                        .setCapitalCode(appName)
                        .setAppLink(loanAppUrl)
                        .setInterest("0")
                        .setDeductAmount("0")
                        .setLateFeeRatio(overdueRatio)
                        .setServiceFee(serviceAmount)
                        .setLateServiceFee("0")
                        .setReceivedCapital(actualAmount)
                        .setPaidAmount(paidAmount)
                        .setReceivedDate(DateUtil.getDate(new Date(repaymentInfo.get("loanDate").toLong()), "yyyy-MM-dd"))
                        .setRepaymentDate(DateUtil.getDate(new Date(repaymentInfo.get("deadline").toLong()), "yyyy-MM-dd"))
                        .setRemainMoney(remainMoney)
                        .setTotalMoney(repaymentAmount);

                request.setOrderInfo(orderInputVo);

                LOGGER.info("== 构建推送信息 个人信息 开始==,collectionNo:{}", order.getCollectionNo());
                CeOrdersDetailEntity personalInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "baseInfo", order.getOrderNo());
                Any personalInfoJson = JsonIterator.deserialize(personalInfo.getDetailInfo());

                String aadhaarNo = "no";
                String pancardNo = personalInfoJson.get("taxRegNumber").toString();
                String email = "no";
                String mobile = personalInfoJson.get("mobile").toString();
                String name = personalInfoJson.get("userName").toString();
                String state = personalInfoJson.get("address").get("state").toString();
                String city = personalInfoJson.get("address").get("city").toString();
                String address = personalInfoJson.get("address").get("addressLine1").toString();
                String gender = personalInfoJson.get("sex").toString();
                String pinCode = personalInfoJson.get("postalCode").toString().length() > 6 ? "no" : personalInfoJson.get("postalCode").toString();
                String birthDay = DateUtil.getDate(new Date(personalInfoJson.get("birthDate").toLong()), "yyyy-MM-dd");

                CeOrdersDetailEntity contactInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactInfo", order.getOrderNo());
                List<Any> contactInfoJson = JsonIterator.deserialize(contactInfo.getDetailInfo()).asList();

                String parentName = "no";
                String parentPhone = "no";
                String friendName = "no";
                String friendMobile = "no";
                if (contactInfoJson.size() >= 2) {
                    parentName = contactInfoJson.get(0).get("name").toString();
                    parentPhone = contactInfoJson.get(0).get("phone").toString();
                    friendName = contactInfoJson.get(1).get("name").toString();
                    friendMobile = contactInfoJson.get(1).get("phone").toString();
                }


                CeOrdersDetailEntity contactUrlEntity = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());


                CeOrdersDetailEntity iamges = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "images", order.getOrderNo());
                List<Any> anies = JsonIterator.deserialize(iamges.getDetailInfo()).asList();

                List<String> images = new ArrayList<>();
                anies.forEach(v -> {
                    images.add(v.toString());
                });

                ClUserInfoInputVo userInfoInputVo = new ClUserInfoInputVo().setUserLanguage("").setAadhaarNo(aadhaarNo).setPanCardNo(pancardNo).setAddress(address).setBirthday(birthDay).setCity(city).setEmail(email)

                        .setContact1Mobile(parentPhone).setContact1Name(parentName).setContact1Relative(1)

                        .setContact2Mobile(friendMobile).setContact2Name(friendName).setContact2Relative(6)

                        .setEducation(0).setKycNo(aadhaarNo).setMobile(mobile)

                        .setMarriedStatus(0).setName(name).setPinCode(pinCode).setState(state)

                        .setSex("female".equals(gender) ? 0 : 1).setContactUrl(contactUrlEntity.getDetailInfo()).setImages(images);

                request.setUserInfo(userInfoInputVo);

                LOGGER.info("== 构建推送信息 完成==,collectionNo:{}", order.getCollectionNo());

                CePushLogEntity pushLogEntity = pushLogDao.selectByCollectionNo(order.getCollectionNo());
                if (pushLogEntity == null) {
                    pushLogEntity = new CePushLogEntity().setCollectionNo(order.getCollectionNo()).setDetailInfo(JsonStream.serialize(request)).setStatus(1);
                    pushLogDao.insert(pushLogEntity);
                } else {
                    pushLogEntity.setDetailInfo(JsonStream.serialize(request));
                    pushLogDao.updateByPrimaryKey(pushLogEntity);
                }


                LOGGER.info("== 构建推送信息 保存信息完成==,collectionNo:{}", order.getCollectionNo());
                order.setSyncStatus(OrderSyncStatusEnum.data_ready.getStatus());
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 构建推送信息 发生异常==,collectionNo:{}", order.getCollectionNo(), e);
                order.setSyncStatus(OrderSyncStatusEnum.data_fail.getStatus());
                ordersDao.updateByPrimaryKey(order);
            }
        });

    }

    @Override
    public void pushDataToCollection(CeAgentAccountEntity agentAccount) {
        super.pushDataToCollection(agentAccount);
    }

    /**
     * 获取新的借贷信息的详细内容是需要 在这个方法执行之前的
     *
     * @param agentAccount
     */
    @Override
    public void checkOrdersPaidStatus(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 检查订单支付情况 ==");
        List<CeOrdersEntity> waitingPaidCheckOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.updated.getStatus());
        if (CollectionUtils.isEmpty(waitingPaidCheckOrders)) {
            LOGGER.info("== 检查订单支付情况 没有状态更新的订单==,size:{}", waitingPaidCheckOrders.size());
            return;
        }

        LOGGER.info("== 检查订单支付情况==,size:{}", waitingPaidCheckOrders.size());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));
        String url = merchant.getApiDomain() + "/api/cm_dunning_case/page";
        JSONObject successParams = new JSONObject();
        JSONObject successParam = new JSONObject();
        successParam.put("pageNo", 1);
        successParam.put("pageSize", 100);
        successParam.put("status", "SUCCESS");
        successParam.put("filterAllCase", false);
        successParams.put("query", successParam);
        long st = System.currentTimeMillis();
        String stt = MD5.md5("#cG8wbGttMW5ibG16eDZoYQ#3XELTZUO#" + st);
        String[] cmds = {"curl", "--location", "--request", "POST", url,
                "--header", "Content-Type: application/json",
                "--header", "lang: en-us",
                "--header", "customer: 3XELTZUO",
                "--header", "auth:" + headers.get("auth"),
                "--header", "Referer: " + merchant.getApiDomain() + "/cm-dunning-case-list",
                "--header", "accept: application/json",
                "--header", "accept-encoding: gzip, deflate, br",
                "--header", "accept-language: zh-CN,zh;q=0.9",
                "--header", "content-type: application/json; charset=utf-8",
                "--header", "origin: " + merchant.getApiDomain(),
                "--header", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"",
                "--header", "st:" + st,
                "--header", "stt:" + stt,
                "--header", "sec-ch-ua-mobile: ?0",
                "--header", "sec-ch-ua-platform: \"macOS\"",
                "--header", "sec-fetch-dest: empty",
                "--header", "sec-fetch-mode: cors",
                "--header", "sec-fetch-site: same-origin",
                "--header", "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
                "--data-raw", successParams.toString()};
        String successResult = execCurl(cmds);
        Any successResultJson = JsonIterator.deserialize(successResult).get("page");
        if (JsonIterator.deserialize(successResult).get("status").toInt() != 0) {
            LOGGER.info("== 订单详情异常 ==");
            return;
        }
        List<Any> successResultsList = successResultJson.get("content").asList();
        waitingPaidCheckOrders.forEach(order -> {
            LOGGER.info("== 已还款订单列表 ==,historyResultsList:{}", JsonStream.serialize(successResultsList));

            boolean isRepay = false;
            double needRepayAmount =0;
            String successLoanAppId = JsonIterator.deserialize(order.getOrderInfo()).get("cmOrder").get("thirdId").toString();
            for (int i = 0; i < successResultsList.size(); i++) {
                String loanAppId = successResultsList.get(i).get("cmOrder").get("thirdId").toString();
                if (loanAppId.equals(successLoanAppId)) {
                    needRepayAmount = successResultsList.get(i).get("cmOrder").get("needRepayAmount").toDouble();
                    isRepay = true;
                    break;
                }
            }


            if (isRepay) {
                LOGGER.info("== 订单已还款 ==,OrderNo:{}", order.getOrderNo());
                order.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
                order.setStatus(OrderStatusEnum.paid_update.getStatus());
                order.setRepayType(needRepayAmount>0?2:1);
                ordersDao.updateByPrimaryKey(order);
                return;
            }
            LOGGER.info("== 订单未还款，移除订单 ==,orderNo:{}", order.getOrderNo());
            order.setStatus(OrderStatusEnum.removed.getStatus());
            order.setSyncStatus(OrderSyncStatusEnum.need_remove.getStatus());
            ordersDao.updateByPrimaryKey(order);
        });


    }

    @Override
    public void updatePaidOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 开始同步有更新的数据到催收系统 ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_pay_update.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== 开始同步有更新的数据到催收系统 没有还款订单==");
            return;
        }

        LOGGER.info("== 开始同步有更新的数据到催收系统 有还款==,size:{}", todayListBySyncStatusAndAgent.size());
        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                CeOrdersDetailEntity repaymentInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                Any repaymentInfo = JsonIterator.deserialize(repaymentInfoDetail.getDetailInfo());
                String paidAmount = repaymentInfo.get("totalPaidAmount").toString();
                ClRepaymentRequest request = new ClRepaymentRequest()
                        .setDeductAmount("0")
                        .setOrderBillNo(order.getCollectionNo())
                        .setPaidAmount(paidAmount)
                        .setPaidStatus(2)
                        .setPaidType(1)
                        .setRepayBizNo(IdUtils.genId() + "")
                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
                        .setTotalDeductAmount("0")
                        .setTotalPaidAmount(paidAmount)
                        .setTradeNo(order.getCollectionNo());

                HttpHeaders headers = new HttpHeaders();
                headers.set("Content-Type", "application/json;charset=utf-8");

                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl(), requestPush, String.class);
                String responseStr = responseEntity.getBody().toString();
                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl());
                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_success.getStatus());
                } else {
                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
                }
            } catch (Exception e) {
                LOGGER.error("=======  推送collection请求结果 error  ======", e);
                order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
            }
            ordersDao.updateByPrimaryKey(order);
        });


    }


    @Override
    public void updateRemovedOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("==  updateRemovedOrderToCollection 开始同步有更新的数据到催收系统 ==");
//        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_remove.getStatus());
//        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
//            LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 没有需要移除的订单==");
//            return;
//        }
//
//        LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 有数据需要移除==,size:{}", todayListBySyncStatusAndAgent.size());
//        todayListBySyncStatusAndAgent.forEach(order -> {
//            try {
//                CeOrdersDetailEntity repaymentInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
//                Any repaymentInfo = JsonIterator.deserialize(repaymentInfoDetail.getDetailInfo());
//                String paidAmount = repaymentInfo.get("paidAmount").toString().equals("") ? "0" : repaymentInfo.get("paidAmount").toString());
//                ClRepaymentRequest request = new ClRepaymentRequest()
//                        .setDeductAmount("0")
//                        .setOrderBillNo(order.getCollectionNo())
//                        .setPaidAmount(paidAmount)
//                        .setPaidStatus(2)
//                        .setPaidType(1)
//                        .setRepayBizNo(IdUtils.genId() + "")
//                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
//                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
//                        .setTotalDeductAmount("0")
//                        .setTotalPaidAmount(paidAmount)
//                        .setTradeNo(order.getCollectionNo());
//
//                HttpHeaders headers = new HttpHeaders();
//                headers.set("Content-Type", "application/json;charset=utf-8");
//
//                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
//                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl()_remove, requestPush, String.class);
//                String responseStr = responseEntity.getBody().toString();
//                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl()_remove);
//                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
//                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_success.getStatus());
//                } else {
//                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//                }
//            } catch (Exception e) {
//                LOGGER.error("=======  推送collection请求结果 error  ======", e);
//                order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//            }
//            ordersDao.updateByPrimaryKey(order);
//        });


    }

    @Override
    public void composeNote(CeCommentPushLogEntity ceCommentPushLogEntity) {
        ceCommentPushLogEntity.setStatus(1);
        commentPushLogDao.updateByPrimaryKey(ceCommentPushLogEntity);
    }


    @Override
    public boolean sendNote(CeCommentPushLogEntity ceCommentPushLogEntity) {

        LittleOrangeCashCollectionTagEnum currentTag = LittleOrangeCashCollectionTagEnum.RNR_V2;

        for (LittleOrangeCashCollectionTagEnum e : LittleOrangeCashCollectionTagEnum.values()) {
            if (e.getType().equals(ceCommentPushLogEntity.getTargetType())) {
                currentTag = e;
            }
        }
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceCommentPushLogEntity.getMerchantCode());
        CeAgentAccountEntity account = agentAccountDao.getByAgentCode(ceCommentPushLogEntity.getAgentCode());
        CeOrdersEntity ceOrdersEntity = ordersDao.getTodayOneByOrderNoAndAgentCode(ceCommentPushLogEntity.getOriginNo(), account.getAgentCode());
        Any orderInfo = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
        CeOrdersDetailEntity baseInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(ceMerchantEntity.getMerchantCode(), "baseInfo", ceOrdersEntity.getOrderNo());
        Any baseInfo = JsonIterator.deserialize(baseInfoDetail.getDetailInfo());
        Map<String, String> headers = getHeaders(account);
        String tagUrl = ceMerchantEntity.getApiDomain() + "/api/cm_dunning_tag/list";
        JSONObject tagParams = new JSONObject();
        tagParams.put("query", new JSONObject());
        long st = System.currentTimeMillis();
        String stt = MD5.md5("#cG8wbGttMW5ibG16eDZoYQ#3XELTZUO#" + st);
        String[] tagCmds = {"curl", "--location", "--request", "POST", tagUrl,
                "--header", "Content-Type: application/json",
                "--header", "lang: en-us",
                "--header", "customer: 3XELTZUO",
                "--header", "auth:" + headers.get("auth"),
                "--header", "Referer: " + ceMerchantEntity.getApiDomain() + "/cm-dunning-case-list",
                "--header", "accept: application/json",
                "--header", "accept-encoding: gzip, deflate, br",
                "--header", "accept-language: zh-CN,zh;q=0.9",
                "--header", "content-type: application/json; charset=utf-8",
                "--header", "origin: " + ceMerchantEntity.getApiDomain(),
                "--header", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"",
                "--header", "st:" + st,
                "--header", "stt:" + stt,
                "--header", "sec-ch-ua-mobile: ?0",
                "--header", "sec-ch-ua-platform: \"macOS\"",
                "--header", "sec-fetch-dest: empty",
                "--header", "sec-fetch-mode: cors",
                "--header", "sec-fetch-site: same-origin",
                "--header", "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
                "--data-raw", tagParams.toString()};
        String tagResult = execCurl(tagCmds);
        Any tagResultJson = JsonIterator.deserialize(tagResult);
        LOGGER.info("== LittleOrange 获取催记结果列表 ==,tag:{}", tagResult);
        if (tagResultJson.get("status").toInt() != 0) {
            LOGGER.info("== 获取催记结果失败 ==");
            return false;
        }
        List<Any> list = tagResultJson.get("list").asList();
        String id = "";
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).get("code").toString().equals(currentTag.getShortDesc())) {
                id = list.get(i).get("id").toString();
                break;
            }
        }
        if (id.equals("")) {
            LOGGER.info("== 获取催记结果产生变化，与本地不匹配 ==");
            return false;
        }
        LOGGER.info("== 开始同步催记到甲方 ==");
        try {
            JSONObject params = new JSONObject();
            JSONObject param = new JSONObject();
            param.put("callingMobile", account.getAccount());
            param.put("mobile", baseInfo.get("mobile").toString());
            param.put("relation", "SELF");
            param.put("name", baseInfo.get("userName").toString());
            param.put("cmDunningTagId", id);
            param.put("cmDunningCaseId", orderInfo.get("id").toString());
            params.put("model", param);
            LOGGER.info("== LittleOrange 开始同步催记到甲方D ==,params:{}", JsonStream.serialize(params));
            String noteUrl = ceMerchantEntity.getApiDomain() + "/api/cm_dunning_case_log/persist";
            long st1 = System.currentTimeMillis();
            String stt1 = MD5.md5("#cG8wbGttMW5ibG16eDZoYQ#3XELTZUO#" + st1);
            String[] noteCmds = {"curl", "--location", "--request", "POST", noteUrl,
                    "--header", "Content-Type: application/json",
                    "--header", "lang: en-us",
                    "--header", "customer: 3XELTZUO",
                    "--header", "auth:" + headers.get("auth"),
                    "--header", "Referer: " + ceMerchantEntity.getApiDomain() + "/cm-dunning-case-list",
                    "--header", "accept: application/json",
                    "--header", "accept-encoding: gzip, deflate, br",
                    "--header", "accept-language: zh-CN,zh;q=0.9",
                    "--header", "content-type: application/json; charset=utf-8",
                    "--header", "origin: " + ceMerchantEntity.getApiDomain(),
                    "--header", "st:" + st1,
                    "--header", "stt:" + stt1,
                    "--header", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"",
                    "--header", "sec-ch-ua-mobile: ?0",
                    "--header", "sec-ch-ua-platform: \"macOS\"",
                    "--header", "sec-fetch-dest: empty",
                    "--header", "sec-fetch-mode: cors",
                    "--header", "sec-fetch-site: same-origin",
                    "--header", "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
                    "--data-raw", params.toString()};
            String result = execCurl(noteCmds);
            LOGGER.info("== LittleOrange 开始同步催记到甲方 ==,res:{}", result);

            if ("0".equals(JsonIterator.deserialize(result).get("status").toString())) {
                LOGGER.info("== 开始同步催记到甲方 success==");
                return true;
            } else {
                LOGGER.error("== 开始同步催记到甲方 error==,msg:{}", JsonIterator.deserialize(result).get("msg").toString());
            }

        } catch (Exception e) {
            LOGGER.error("== 开始同步催记到甲方 exception==", e);
        }
        return false;
    }

    public static final ExecutorService pool = Executors.newFixedThreadPool(5);

    @Override
    public String updateRepaymentLink(String collectionNo, boolean isReduce) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        CeOrdersDetailEntity repaymentInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(ceMerchantEntity.getMerchantCode(), "repaymentInfo", ceOrdersEntity.getOrderNo());
        Any repaymentInfo = JsonIterator.deserialize(repaymentInfoDetail.getDetailInfo());


        long s = System.currentTimeMillis();
        Map<String, String> headers = getHeaders(accountEntity);
        String channelUrl = ceMerchantEntity.getApiDomain() + "/api/cm_order/support_list?id=" + ceOrdersEntity.getOrderNo() + "&test=false";
        LOGGER.info("== 获取LittleOrange 获取还款渠道列表 ==,url:{},cost:{}", channelUrl, System.currentTimeMillis() - s);
        long st = System.currentTimeMillis();
        String stt = MD5.md5("#cG8wbGttMW5ibG16eDZoYQ#3XELTZUO#" + st);
        String[] channelCmds = {"curl", "--location", "--request", "POST", channelUrl,
                "--header", "Content-Type: application/json",
                "--header", "lang: en-us",
                "--header", "customer: 3XELTZUO",
                "--header", "auth:" + headers.get("auth"),
                "--header", "Referer: " + ceMerchantEntity.getApiDomain() + "/cm-dunning-case-list",
                "--header", "accept: application/json",
                "--header", "accept-encoding: gzip, deflate, br",
                "--header", "accept-language: zh-CN,zh;q=0.9",
                "--header", "content-type: application/json; charset=utf-8",
                "--header", "origin: " + ceMerchantEntity.getApiDomain(),
                "--header", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"",
                "--header", "st:" + st,
                "--header", "stt:" + stt,
                "--header", "sec-ch-ua-mobile: ?0",
                "--header", "sec-ch-ua-platform: \"macOS\"",
                "--header", "sec-fetch-dest: empty",
                "--header", "sec-fetch-mode: cors",
                "--header", "sec-fetch-site: same-origin",
                "--header", "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
                "--data-raw", new JSONObject().toString()};
        String channelResult = execCurl(channelCmds);
        LOGGER.info("== 获取LittleOrange 获取还款渠道列表 ==,url:{},res:{}", channelUrl, channelResult);
        Any channelResultJson = JsonIterator.deserialize(channelResult);
        if (channelResultJson.get("status").toInt() != 0) {
            return "";
        }

        List<Any> channelList = channelResultJson.get("list").asList();
        LOGGER.info("== 获取LittleOrange 获取还款渠道列表 ==,list:{}", channelList);

        if (CollectionUtils.isEmpty(channelList)) {
            LOGGER.info("== 获取LittleOrange 获取还款渠道列表出错 ==,list:{}", channelList);
            return "";
        }
        String link = "";
        String url = ceMerchantEntity.getApiDomain() + "/api/cm_order/create_replay_link";
        int count = channelList.size();

        List<String> list = Lists.newArrayListWithCapacity(count);
        CountDownLatch latch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {
            String methodId = channelList.get(i).get("id").toString();
            String name = channelList.get(i).get("name").toString();
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        String link1 = getLink("IMMEDIATE", url, methodId, repaymentInfo.get("needRepayAmount").toInt(), repaymentInfo.get("id").toString(), headers.get("auth"), name, ceMerchantEntity.getApiDomain());
                        list.add(link1);
                    } catch (Exception e) {
                        LOGGER.error("获取LittleOrange LO获取还款链接异常1", e);
                    } finally {
                        latch.countDown();
                    }
                }
            });
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            LOGGER.error("获取LittleOrange LO获取还款链接异常2", e);
        }

        for (int i = 0; i < list.size(); i++) {
            link = link + list.get(i) + " ,";
        }


        LOGGER.info("== 获取还款渠道列表2 ==,url:{},cost:{}", channelUrl, System.currentTimeMillis() - s);

        CeRepaymentLinkEntity entity = new CeRepaymentLinkEntity();
        entity.setMerchantCode(ceMerchantEntity.getMerchantCode());
        entity.setAgentCode(accountEntity.getAgentCode());
        entity.setCollectionNo(ceOrdersEntity.getCollectionNo());
        entity.setStatus(0);
        entity.setOtherInfo("");
        entity.setPaymentUrl(link);
        repaymentLinkDao.insert(entity);
        return tt(link, apolloConfigUtil.getLoPayLinkKeyRank());
    }

    @Override
    public String updateExtensionRepaymentLink(String collectionNo,boolean isOpen) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        Any orderInfoJson = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
        CeOrdersDetailEntity repaymentInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(ceMerchantEntity.getMerchantCode(), "repaymentInfo", ceOrdersEntity.getOrderNo());
        Any repaymentInfo = JsonIterator.deserialize(repaymentInfoDetail.getDetailInfo());


        Map<String, String> headers = getHeaders(accountEntity);
        headers.put("referer", "https://client.dcidefjbmskjer.com/cm-dunning-case-list");
        String channelUrl = ceMerchantEntity.getApiDomain() + "/api/cm_order/support_list?id=" + ceOrdersEntity.getOrderNo() + "&test=false";
        LOGGER.info("== 获取LittleOrange 获取还款渠道列表 ==,url:{}", channelUrl);
        long st = System.currentTimeMillis();
        String stt = MD5.md5("#cG8wbGttMW5ibG16eDZoYQ#3XELTZUO#" + st);
        String[] channelCmds = {"curl", "--location", "--request", "POST", channelUrl,
                "--header", "Content-Type: application/json",
                "--header", "lang: en-us",
                "--header", "customer: 3XELTZUO",
                "--header", "auth:" + headers.get("auth"),
                "--header", "Referer: " + ceMerchantEntity.getApiDomain() + "/cm-dunning-case-list",
                "--header", "accept: application/json",
                "--header", "accept-encoding: gzip, deflate, br",
                "--header", "accept-language: zh-CN,zh;q=0.9",
                "--header", "content-type: application/json; charset=utf-8",
                "--header", "origin: " + ceMerchantEntity.getApiDomain(),
                "--header", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"",
                "--header", "st:" + st,
                "--header", "stt:" + stt,
                "--header", "sec-ch-ua-mobile: ?0",
                "--header", "sec-ch-ua-platform: \"macOS\"",
                "--header", "sec-fetch-dest: empty",
                "--header", "sec-fetch-mode: cors",
                "--header", "sec-fetch-site: same-origin",
                "--header", "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
                "--data-raw", new JSONObject().toString()};
        String channelResult = execCurl(channelCmds);
        LOGGER.info("== 获取LittleOrange 获取还款渠道列表 ==,url:{},res:{}", channelUrl, channelResult);
        Any channelResultJson = JsonIterator.deserialize(channelResult);
        if (channelResultJson.get("status").toInt() != 0) {
            return "";
        }

        List<Any> channelList = channelResultJson.get("list").asList();
        LOGGER.info("== 获取LittleOrange 获取还款渠道列表 ==,list:{}", channelList);

        if (CollectionUtils.isEmpty(channelList)) {
            LOGGER.info("== 获取LittleOrange 获取还款渠道列表出错 ==,list:{}", channelList);
            return "";
        }
        String link = "";
        String url = ceMerchantEntity.getApiDomain() + "/api/cm_order/create_replay_link";
        int count = channelList.size();

        List<String> list = Lists.newArrayListWithCapacity(count);
        CountDownLatch latch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {
            String methodId = channelList.get(i).get("id").toString();
            String name = channelList.get(i).get("name").toString();
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        String link1 = getLink("DELAY", url, methodId, repaymentInfo.get("needDelayAmount").toInt(), repaymentInfo.get("id").toString(), headers.get("auth"), name, ceMerchantEntity.getApiDomain());
                        list.add(link1);
                    } catch (Exception e) {
                        LOGGER.error("获取LittleOrange LO获取还款链接异常3", e);
                    } finally {
                        latch.countDown();
                    }
                }
            });
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            LOGGER.error("获取LittleOrange LO获取还款链接异常4", e);
        }


        for (int i = 0; i < list.size(); i++) {
            link = link + list.get(i) + " ,";
        }
        CeRepaymentLinkEntity entity = new CeRepaymentLinkEntity();
        entity.setMerchantCode(ceMerchantEntity.getMerchantCode());
        entity.setAgentCode(accountEntity.getAgentCode());
        entity.setCollectionNo(ceOrdersEntity.getCollectionNo());
        entity.setStatus(1);
        entity.setOtherInfo("");
        entity.setPaymentUrl(link);
        repaymentLinkDao.insert(entity);
        return tt(link, apolloConfigUtil.getLoPayLinkKeyRank());
    }

    @Override
    public String addPaymentOrder(String orderNo, String fileName, String fileUrl, String utr, String remark, String amount) {
        CeOrdersEntity ordersEntity = ordersDao.getTodayOneByOrderNo(orderNo);
        CeAgentAccountEntity agentAccount = agentAccountDao.getByAgentCode(ordersEntity.getAgentCode());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(ordersEntity.getMerchantCode());
        Map<String, String> headers = getHeaders(agentAccount);
        try {
            String url = merchant.getApiDomain() + "/api/file/upload?image=true&token=";
            long st = System.currentTimeMillis();
            String stt = MD5.md5("#cG8wbGttMW5ibG16eDZoYQ#3XELTZUO#" + st);
            File file = getFile(fileUrl);
            String absolutePath = file.getAbsolutePath();
            LOGGER.info("== LittleOrange补单获取图片 ==,absolutePath:{}", absolutePath);

            LOGGER.info("== absolutePath ==,absolutePath:{}",absolutePath);
            String[] cmds = {"curl", "--location", "--request", "POST", url,
                    "--header", "content-type:  multipart/form-data",
                    "--header", "lang: en-us",
                    "--header", "customer: 3XELTZUO",
                    "--header", "auth:" + headers.get("auth"),
                    "--header", "Referer: " + merchant.getApiDomain() + "/cm-dunning-case-list",
                    "--header", "accept: application/json",
                    "--header", "accept-encoding: gzip, deflate, br",
                    "--header", "accept-language: zh-CN,zh;q=0.9",
                    "--header", "content-type: application/json; charset=utf-8",
                    "--header", "origin: " + merchant.getApiDomain(),
                    "--header", "st:" + st,
                    "--header", "stt:" + stt,
                    "--header", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"",
                    "--header", "sec-ch-ua-mobile: ?0",
                    "--header", "sec-ch-ua-platform: \"macOS\"",
                    "--header", "sec-fetch-dest: empty",
                    "--header", "sec-fetch-mode: cors",
                    "--header", "sec-fetch-site: same-origin",
                    "--header", "x-requested-with:  XMLHttpRequest",
                    "--header", "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
                    "--form", "file=@"+absolutePath};
            String successResult = execCurl(cmds);
            LOGGER.info("== LittleOrange补单上传图片 ==,uploadResult:{}", successResult);

            Any orderInfo = JsonIterator.deserialize(ordersEntity.getOrderInfo());
            JSONObject params = new JSONObject();
            params.put("cmDunningCaseId", orderInfo.get("id").toString());
            JSONArray param = new JSONArray();
            param.add(JsonIterator.deserialize(successResult).get("model").get("id").toString());
            params.put("images", param);
            String url1 = merchant.getApiDomain() + "/api/cm_repay_proof/upload_proof";
            long st1 = System.currentTimeMillis();
            String stt1 = MD5.md5("#cG8wbGttMW5ibG16eDZoYQ#3XELTZUO#" + st1);
            String[] cmds1 = {"curl", "--location", "--request", "POST", url1,
                    "--header", "content-type:application/json",
                    "--header", "lang: en-us",
                    "--header", "customer: 3XELTZUO",
                    "--header", "auth:" + headers.get("auth"),
                    "--header", "Referer: " + merchant.getApiDomain() + "/cm-dunning-case-list",
                    "--header", "accept: application/json",
                    "--header", "accept-encoding: gzip, deflate, br",
                    "--header", "accept-language: zh-CN,zh;q=0.9",
                    "--header", "content-type: application/json; charset=utf-8",
                    "--header", "origin: " + merchant.getApiDomain(),
                    "--header", "st:" + st1,
                    "--header", "stt:" + stt1,
                    "--header", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"",
                    "--header", "sec-ch-ua-mobile: ?0",
                    "--header", "sec-ch-ua-platform: \"macOS\"",
                    "--header", "sec-fetch-dest: empty",
                    "--header", "sec-fetch-mode: cors",
                    "--header", "sec-fetch-site: same-origin",
                    "--header", "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
                    "--data-raw", params.toString()};
            String result = execCurl(cmds1);
            LOGGER.info("==result==,result:{}",result);
            if (JsonIterator.deserialize(result).get("status").toInt() == 0) {//提交成功
                LOGGER.info("== LittleOrange补单成功 ==,orderNo:{}", orderNo);
                return "success";
            } else {//重复提交
                LOGGER.info("== LittleOrange补单失败 ==,orderNo:{}", orderNo);
                return "fail";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "fail";
    }

    public static File getFile(String url) throws Exception {
        //对本地文件命名
        String fileName = url.substring(url.lastIndexOf("/") + 1)+".jpeg";
        File file = null;

        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            file = File.createTempFile("net_url", fileName);
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return file;
    }

    public static String tt(String res, String target) {
        if ("all".equalsIgnoreCase(target)) {
            return res;
        }

        List<String> payLink = new ArrayList<>();
        String[] split1 = target.split(",");
        String[] split = res.split(",");
        for (String t : split1) {
            for (String link : split) {
                if (link.toLowerCase().contains(t)) {
                    payLink.add(link);
                }
            }
        }


        for (String link : split) {
            if (!payLink.contains(link)) {
                payLink.add(link);
            }
        }

        StringBuilder rr = new StringBuilder();
        for (String s : payLink) {
            rr.append(s).append(",\r\n");
        }


        return rr.toString();
    }

    @Override
    public String queryPaymentOrderResult(String orderNo, String utr) {
        CeOrdersEntity ordersEntity = ordersDao.getTodayOneByOrderNo(orderNo);
        CeAgentAccountEntity agentAccount = agentAccountDao.getByAgentCode(ordersEntity.getAgentCode());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(ordersEntity.getMerchantCode());
        Any orderInfo = JsonIterator.deserialize(ordersEntity.getOrderInfo());
        if (ordersEntity.getStatus() == 4){
            return "Paid";
        }
        Map<String, String> headers = getHeaders(agentAccount);
        String url = merchant.getApiDomain() + "/api/cm_repay_proof/page";
        JSONObject params = new JSONObject();
        JSONObject param = new JSONObject();
        param.put("pageNo", 1);
        param.put("pageSize", 100);
        param.put("cmDunningCaseId", orderInfo.get("id").toString());
        params.put("query", param);
        long st = System.currentTimeMillis();
        String stt = MD5.md5("#cG8wbGttMW5ibG16eDZoYQ#3XELTZUO#" + st);
        String[] cmds = {"curl", "--location", "--request", "POST", url,
                "--header", "Content-Type: application/json",
                "--header", "lang: en-us",
                "--header", "customer: 3XELTZUO",
                "--header", "auth:" + headers.get("auth"),
                "--header", "Referer: " + merchant.getApiDomain() + "/cm-dunning-case-list",
                "--header", "accept: application/json",
                "--header", "accept-encoding: gzip, deflate, br",
                "--header", "accept-language: zh-CN,zh;q=0.9",
                "--header", "content-type: application/json; charset=utf-8",
                "--header", "origin: " + merchant.getApiDomain(),
                "--header", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"",
                "--header", "st:" + st,
                "--header", "stt:" + stt,
                "--header", "sec-ch-ua-mobile: ?0",
                "--header", "sec-ch-ua-platform: \"macOS\"",
                "--header", "sec-fetch-dest: empty",
                "--header", "sec-fetch-mode: cors",
                "--header", "sec-fetch-site: same-origin",
                "--header", "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
                "--data-raw", params.toString()};
        String result = execCurl(cmds);
        LOGGER.info("== 查询LittleOrange补单结果 ==,result:{}",result);
        List<Any> list = JsonIterator.deserialize(result).get("page").get("content").asList();
        if (CollectionUtils.isNotEmpty(list)){
            String message = list.get(list.size()-1).get("message").toString();
            return message;
        }
        return "";
    }

    @Override
    public String checkOrdersPaid(String orderNo) {
        CeOrdersEntity ordersEntity = ordersDao.getTodayOneByOrderNo(orderNo);
        CeAgentAccountEntity agentAccount = agentAccountDao.getByAgentCode(ordersEntity.getAgentCode());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(ordersEntity.getMerchantCode());
        Map<String, String> headers = getHeaders(agentAccount);

        String url = merchant.getApiDomain() + "/api/cm_dunning_case/page";
        JSONObject successParams = new JSONObject();
        JSONObject successParam = new JSONObject();
        successParam.put("pageNo", 1);
        successParam.put("pageSize", 100);
        successParam.put("status", "SUCCESS");
        successParam.put("filterAllCase", false);
        successParams.put("query", successParam);
        long st = System.currentTimeMillis();
        String stt = MD5.md5("#cG8wbGttMW5ibG16eDZoYQ#3XELTZUO#" + st);
        String[] cmds = {"curl", "--location", "--request", "POST", url,
                "--header", "Content-Type: application/json",
                "--header", "lang: en-us",
                "--header", "customer: 3XELTZUO",
                "--header", "auth:" + headers.get("auth"),
                "--header", "Referer: " + merchant.getApiDomain() + "/cm-dunning-case-list",
                "--header", "accept: application/json",
                "--header", "accept-encoding: gzip, deflate, br",
                "--header", "accept-language: zh-CN,zh;q=0.9",
                "--header", "content-type: application/json; charset=utf-8",
                "--header", "origin: " + merchant.getApiDomain(),
                "--header", "st:" + st,
                "--header", "stt:" + stt,
                "--header", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"",
                "--header", "sec-ch-ua-mobile: ?0",
                "--header", "sec-ch-ua-platform: \"macOS\"",
                "--header", "sec-fetch-dest: empty",
                "--header", "sec-fetch-mode: cors",
                "--header", "sec-fetch-site: same-origin",
                "--header", "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
                "--data-raw", successParams.toString()};
        String successResult = execCurl(cmds);
        Any successResultJson = JsonIterator.deserialize(successResult).get("page");
        if (JsonIterator.deserialize(successResult).get("status").toInt() != 0) {
            LOGGER.info("== 订单详情异常 ==");
            return "no order found";
        }
        List<Any> successResultsList = successResultJson.get("content").asList();
        LOGGER.info("== 已还款订单列表 ==,historyResultsList:{}", JsonStream.serialize(successResultsList));

        boolean isRepay = false;
        String successLoanAppId = JsonIterator.deserialize(ordersEntity.getOrderInfo()).get("cmOrder").get("thirdId").toString();
        for (int i = 0; i < successResultsList.size(); i++) {
            String loanAppId = successResultsList.get(i).get("cmOrder").get("thirdId").toString();
            if (loanAppId.equals(successLoanAppId)) {
                isRepay = true;
                break;
            }
        }


        if (isRepay) {
            LOGGER.info("== 订单已还款 ==,OrderNo:{}", ordersEntity.getOrderNo());
            if (!ordersEntity.getSyncStatus().equals(OrderSyncStatusEnum.pay_update_success.getStatus())) {
                ordersEntity.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
            }
            ordersEntity.setStatus(OrderStatusEnum.paid_update.getStatus());
            ordersDao.updateByPrimaryKey(ordersEntity);
            return "paid already!";
        }
        return "no paid";
    }

    public static String getLink(String repayType, String url, String methodId, int needRepayAmount, String id, String auth, String name, String apiDomain) {
        String link = "";
        JSONObject params = new JSONObject();
        params.put("repayType", repayType);
        params.put("repayMethodId", methodId);
        params.put("amount", needRepayAmount);
        params.put("cmOrderId", id);
        LOGGER.info("== 获取LittleOrange还款链接 ==,url:{}", url);
        long st = System.currentTimeMillis();
        String stt = MD5.md5("#cG8wbGttMW5ibG16eDZoYQ#3XELTZUO#" + st);
        String[] cmds = {"curl", "--location", "--request", "POST", url,
                "--header", "Content-Type: application/json",
                "--header", "lang: en-us",
                "--header", "customer: 3XELTZUO",
                "--header", "auth:" + auth,
                "--header", "Referer: " + apiDomain + "/cm-dunning-case-list",
                "--header", "accept: application/json",
                "--header", "accept-encoding: gzip, deflate, br",
                "--header", "accept-language: zh-CN,zh;q=0.9",
                "--header", "content-type: application/json; charset=utf-8",
                "--header", "origin: " + apiDomain,
                "--header", "st:" + st,
                "--header", "stt:" + stt,
                "--header", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"",
                "--header", "sec-ch-ua-mobile: ?0",
                "--header", "sec-ch-ua-platform: \"macOS\"",
                "--header", "sec-fetch-dest: empty",
                "--header", "sec-fetch-mode: cors",
                "--header", "sec-fetch-site: same-origin",
                "--header", "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
                "--data-raw", params.toString()};
        String result = execCurl(cmds);
        LOGGER.info("== 获取LittleOrange还款链接 ==,orderId:{},url:{},res:{}", id, url, result);
        Any resultJson = JsonIterator.deserialize(result);
        if (resultJson.get("status").toInt() == 0) {
            link = name + ": " + resultJson.get("model").get("payInfo").toString();
            LOGGER.info("== 获取LittleOrange还款链接 ==,link:{}", link);
        }
        return link;
    }

    public static void main(String[] args) {
    }


//    static class Worker implements Runnable {
//        final CyclicBarrier barrier;
//        String repayType;
//        String url;
//        String id;
//        String methodId;
//        String auth;
//        int i;
//        int needRepayAmount;
//
//        public Worker(String repayType, int i, String url, String methodId, int needRepayAmount, String id, String auth, CyclicBarrier barrier) {
//            this.url = url;
//            this.repayType = repayType;
//            this.methodId = methodId;
//            this.id = id;
//            this.i = i;
//            this.needRepayAmount = needRepayAmount;
//            this.auth = auth;
//            this.barrier = barrier;
//        }
//
//        @Override
//        public void run() {
//            try {
//                JSONObject params = new JSONObject();
//                params.put("repayType", repayType);
//                params.put("repayMethodId", methodId);
//                params.put("amount", needRepayAmount);
//                params.put("cmOrderId", id);
//                LOGGER.info("== 获取LittleOrange还款链接 ==,url:{}", url);
//                String[] cmds = {"curl", "--location", "--request", "POST", url,
//                        "--header", "Content-Type: application/json",
//                        "--header", "lang: en-us",
//                        "--header", "customer: 3XELTZUO",
//                        "--header", "auth:" + auth,
//                        "--header", "Referer: "+merchant.getApiDomain()+"/cm-dunning-case-list",
//                        "--data-raw", params.toString()};
//                String result = execCurl(cmds);
//                LOGGER.info("== 获取LittleOrange还款链接 ==,url:{},res:{}", url, result);
//                Any resultJson = JsonIterator.deserialize(result);
//                if (resultJson.get("status").toInt() == 0) {
//                    String payInfo = resultJson.get("model").get("payInfo").toString();
//                    link += "Link" + (i + 1) + ":" + payInfo + "\n   ";
//                    LOGGER.info("== 获取还款链接 ==,link:{}", link);
//                }
//                this.barrier.await();
//            } catch (InterruptedException | BrokenBarrierException e) {
//                e.printStackTrace();
//            }
//
//        }

//    }

}
